<template>
  <div class="app-container">
    <!-- 查询 -->
    <tl-list-search ref="search" :query-param="queryParam" @search="doQuery" :isDisplayDefaultSearch="false" v-if="isHeaderDisplay">
      <template slot="search">
        <el-form-item label="部门名称" label-width="70px">
          <el-select style="width:100%" v-model="createdepart" placeholder="请选择部门名称" filterable collapse-tags clearable multiple @change="doQueryConcatCreateDepart">
            <el-option v-for="item in codeModel.mpmCreateDepartList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" label-width="70px">
          <el-input v-model="queryParam.qry_projectname" placeholder="名称或编号" @keyup.enter.native="doQuery"></el-input>
        </el-form-item>
        <!-- <el-form-item label="项目级别">
          <el-select v-model="projectlevel" multiple placeholder="请选择项目级别" style="width:190px" @change="doQueryConcatProjectLevel">
            <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code"> </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="项目经理" label-width="70px">
          <el-input v-model="queryParam.qry_projectmanager" placeholder="工号或姓名" @keyup.enter.native="doQuery"> </el-input>
        </el-form-item>
        <el-form-item label="系统部支持">
          <el-select v-model="queryParam.qry_needsupport" placeholder="是否需要系统部支持" filterable collapse-tags clearable>
            <el-option v-for="item in codeModel.needsupportList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
      </template>
      <template slot="button">
        <el-button type="primary" icon="el-icon-zoom-in" @click="openDeatailSearchDialog">详细查询</el-button>
      </template>
      <template slot="button">
        <el-button type="primary" icon="el-icon-zoom-in" @click="resetQuery">重置</el-button>
      </template>
    </tl-list-search>
    <!-- 工具栏 -->
    <tl-list-toolbar ref="toolbar" :refMainTable="$refs.mainTable" currentModuleTableCode="mpmProject/main" :startColumn="3" :isDisplayAdd="false" :isDisplayDeleteBatch="false" @exportExcel="doExportExcel" :isDisplayExport="false" @deleteBatch="doDeleteBatch" @refresh="doRefresh" @columnCustomize="doColumnCustomize" @displaySearch="doDisplaySearch" :disableDeleteBatch="selectedRowKeys.length <= 0">
      <template slot="left-btn">
        <!-- <el-button class="filter-item" type="primary" icon="el-icon-download" @click="doExportExcel" v-hasPermission="['sys:excel:export']">导出</el-button> -->
        <el-dropdown split-button type="primary">
          <i class="el-icon-edit"></i>
          统计相关
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="openSummaryDialog('managerForm')">统计(按项目经理)</el-dropdown-item>
            <el-dropdown-item @click.native="openSummaryDialog('deptForm')">统计(按部门)</el-dropdown-item>
            <el-dropdown-item @click.native="openSummaryDialog('productLineForm')">统计(按产品线)</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button class="filter-item" type="primary" @click.native="openChangeManager()" v-if="isCFOForThisProject">项目经理交接</el-button>
        <!-- <el-button type="primary" icon="el-icon-zoom-in" @click="openDeatailSearchDialog">详细查询</el-button>
                        <el-button type="primary" icon="el-icon-zoom-in" @click="resetQuery">重置</el-button> -->
      </template>
    </tl-list-toolbar>
    <div>
      <!-- 列表选择 -->
      <!-- <div class="table-alert-div" ref="selector">
        <el-alert type="success" :closable="false" class="tl-table-alert-info" effect="light">
          <template slot="title">
            已选择&nbsp;<a class="tl-table-alert-info-a1">{{ selectedRowKeys.length }}</a>项&nbsp;&nbsp;
            <a class="tl-table-alert-info-a2" @click="doClearSelected">全部清空</a>
          </template>
        </el-alert>
      </div> -->

      <!--表格渲染-->
      <el-table class="tl-table" :style="{ '--tableWidth': tableWidth }" ref="mainTable" :height="tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" row-key="id" border fit :row-class-name="doChangeRowClassName" @expand-change="expandChange" :expand-row-keys="expands">
        <!-- <el-table-column type="selection" width="55px" fixed="left" :selectable="doDisableCheckBox"></el-table-column> -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <tl-customer-task ref="customerTaskForm" :customerTaskList="props.row.customertask" :projectInfo="{ projectcode: props.row.projectcode }"></tl-customer-task>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
        <!-- <el-table-column prop="deptname" label="省份" width="95px" sortable="custom" sort-by="deptname" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column prop="projectname" label="项目名称" min-width="300px" sortable="custom" sort-by="projectname" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="dispprojectlevel" label="项目级别" width="80px" sortable="custom" sort-by="projectlevel" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="demandbegindate" label="需求上报日期" width="105px" sortable="custom" sort-by="demandbegindate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="demandenddate" label="需求截止日期" width="105px" sortable="custom" sort-by="demandenddate" align="center" header-align="center" :formatter="dateFormat" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="bidbegindate" width="100px" label="挂网日期" align="center" header-align="center" :show-overflow-tooltip="true" :formatter="dateFormat"></el-table-column>
        <el-table-column prop="bidenddate" width="100px" label="开标日期" align="center" header-align="center" :show-overflow-tooltip="true" :formatter="dateFormat"></el-table-column>
        <el-table-column prop="background" label="项目背景" width="240px" sortable="custom" sort-by="background" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="target" label="项目目标" width="200px" sortable="custom" sort-by="target" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="summary" label="总体策划" width="200px" sortable="custom" sort-by="summary" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="participatemoney" label="项目金额(万元)"  width="130px" sortable="custom" sort-by="participatemoney" align="right" header-align="center" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="clientname" label="客户名称" width="250px" sortable="custom" sort-by="clientname" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="clientsupport" label="客户决策链支持度" width="200px" sortable="custom" sort-by="clientsupport" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="clientdemand" label="客户需求分析" width="200px" sortable="custom" sort-by="clientdemand" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="clientdept" label="客户部门" width="100px" sortable="custom" sort-by="clientdept" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <!-- <el-table-column prop="decisionmode" label="客户决策模式" width="200px" sortable="custom" sort-by="decisionmode" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <el-table-column prop="dispprojectstate" label="项目阶段" width="115px" sortable="custom" sort-by="projectstate" align="center" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="description" label="备注" width="150px" sortable="custom" sort-by="description" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column prop="productrange" label="内部产品" width="260px" sortable="custom" align="left" header-align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.productrange && scope.row.productrange.length > 0 && Array.isArray(scope.row.productrange)">
              <el-row v-for="(item, index) in scope.row.productrange" :key="index">
                <span>{{ item.productType }}</span>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="productoutrange" label="外部产品" width="200px" sortable="custom" align="left" header-align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="scope.row.productoutrange && scope.row.productoutrange.length > 0 && Array.isArray(scope.row.productoutrange)">
              <el-row v-for="(item, index) in scope.row.productoutrange" :key="index">
                <span>{{ item.productOutType }}</span>
              </el-row>
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="importance" label="项目概述" width="200px" sortable="custom" sort-by="importance" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
        <!-- <el-table-column prop="productrange" label="涉及产品范围" width="200px" sortable="custom" sort-by="productrange" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column> -->
      <el-table-column label="操作" width="100px" v-slot="scope" fixed="right">
          <el-dropdown trigger="hover">
            <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu>
              <el-dropdown-item icon="el-icon-circle-check" @click.native="projectMark(scope.row.id, '1')" v-if="scope.row.markflag === '0'">关注</el-dropdown-item>
              <el-dropdown-item icon="el-icon-circle-close" @click.native="projectMark(scope.row.id, '2')" v-if="scope.row.markflag === '1'">取消关注</el-dropdown-item>
              <el-dropdown-item icon="el-icon-edit" @click.native="openCommentDialog('insertComment', scope.row)">留言</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </el-table>
      <!-- 列表分页 -->
      <el-row class="pagebar" ref="pager">
        <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
      </el-row>
      <tl-edit ref="editForm" @refresh="doRefresh"></tl-edit>
      <tl-supervise-edit ref="superviseeditForm"></tl-supervise-edit>
    </div>
    <tl-manager-summary ref="managerForm" @refresh="doRefresh" :sourceType="sourceType" :queryParams="queryParam"></tl-manager-summary>
    <tl-manager-summary ref="deptForm" @refresh="doRefresh" :sourceType="sourceType" :queryParams="queryParam"></tl-manager-summary>
    <tl-product-line-summary ref="productLineForm" :queryParams="queryParam" @refresh="doRefresh"></tl-product-line-summary>
    <tl-detail-search ref="detailSearch" :queryParams.sync="queryParam" :projectLevel.sync="projectlevel" :createDepart.sync="createdepart" :codeModel="codeModel" @upadateParam="updateParam" @loadData="loadData" @resetQueryParam="resetQuery"></tl-detail-search>
    <tl-mpm-project-change-manager ref="projectChangeManager"></tl-mpm-project-change-manager>
    <insert-comment source-type="MpmProject"  ref="insertComment"></insert-comment>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlSuperviseEdit from '@/views/mpm/mpmProjectSupervise/editView'
import tlEdit from './edit'
import tlManagerSummary from './managerSummary'
import tlProductLineSummary from './productLineSummary'
import tlDetailSearch from '@/views/mpm/mpmProject/DetailSearch'
import tlMpmProjectChangeManager from '@/views/mpm/mpmProjectChangeManager/edit'
import tlCustomerTask from '../mpmCustomerTask/editForSystem'
import insertComment from "../mpmComments/insertComment"

/** 工具类 */
import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
import { filterObjectNull, rmbFormat } from '@tapui/utils/util'
export default {
  name: 'mpmProjectInfo',
  mixins: [mixin_list],
  components: { tlEdit, tlDetailSearch, tlSuperviseEdit, tlManagerSummary, tlProductLineSummary, tlMpmProjectChangeManager, tlCustomerTask, insertComment },
  data() {
    return {
      queryParam: {
        qry_projectlevel: 0,
        qry_purchasepattern: '3,7,9' // 采购模式使用排除法查询（not in），现在排除“电商”、"服务招标采购"、“其他”模式
      },
      sourceType: '',
      projectlevelList: [],
      description: '项目立项-列表查询',
      urlPrefix: '/mpm/projectpolymerization/',
      url: {
        list: '/mpm/projectpolymerization/listForSys',
        queryCodeList: '/mpm/projectpolymerization/dataCodeList',
        isCFO: '/mpm/project/isCFO',
        getProjectChangeManager: '/mpm/projectChangeManager/getProjectChangeManager',
        queryCustomerTaskForSystem: '/mpm/customerTask/queryCustomerTaskForSystem',
        queryCustomerAnalysisForSystem: '/mpm/customerAnalysis/queryCustomerAnalysisForSystem',
        queryTaskForSystem: '/mpm/projectTask/queryTaskForSystem',
        changeOperateMarkState: '/mpm/project/operateMarkState'
      },
      detailSearchVisible: false,
      // 排序参数
      sorterInfo: {
        sidx: 'sortcode',
        sord: 'asc'
      },
      chanceclueList: [],
      urlParam: '?',
      projectlevel: [],
      createdepart: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '本月',
            onClick(picker) {
              const date = new Date()
              const firstDay = new Date(date.getFullYear(), date.getMonth(), 1)
              picker.$emit('pick', [firstDay, new Date()])
            }
          },
          {
            text: '今年至今',
            onClick(picker) {
              const end = new Date()
              const start = new Date(new Date().getFullYear(), 0)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近六个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setMonth(start.getMonth() - 6)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setMonth(start.getMonth() - 12)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      isCFOForThisProject: false,
      // 要展开的行
      expands: [],
      tableWidth: '0px'
    }
  },
  // 消除因页面跳转导致无法消失的tooltip
  deactivated() {
    const tooltip = document.querySelectorAll('.el-tooltip__popper')
    tooltip.forEach((item) => {
      item.style.display = 'none'
    })
  },
  methods: {
    openDeatailSearchDialog() {
      this.$refs.detailSearch.visible = true
    },
    // 接受子组件返回参数
    updateParam(queryParam) {
      this.queryParam = queryParam
    },
    openSummaryDialog(Form) {
      this.$refs[Form].visible = true
      this.sourceType = Form
    },
    // 项目级别多选框
    doQueryConcatProjectLevel(data) {
      if (data.length > 0) {
        this.queryParam.qry_projectlevel = data
          .map((item) => {
            return "'" + item + "'"
          })
          .join(',')
      } else {
        this.queryParam.qry_projectlevel = null
      }
    },
    // 部门名称多选框
    doQueryConcatCreateDepart(data) {
      if (data.length > 0) {
        this.queryParam.query_createdepart = data
          .map((item) => {
            return "'" + item + "'"
          })
          .join(',')
      } else {
        this.queryParam.query_createdepart = null
      }
    },
    // 重置查询条件(子组件调用)
    resetQueryForDetailSearch() {
      this.queryParam = {
        qry_projectlevel: 0,
        qry_purchasepattern: '3,7,9'
      }
      this.param = {}
      this.projectlevel = []
      this.createdepart = []
      this.doQuery()
    },
    // 重置查询条件(页面重置按钮使用)
    resetQuery() {
      this.queryParam = {
        qry_projectlevel: 0,
        qry_purchasepattern: '3,7,9'
      }
      this.param = {}
      this.projectlevel = []
      this.createdepart = []
      this.$refs.detailSearch.resetQueryParam()
      this.doQuery()
    },
    /** 执行查询 */
    doQuery() {
      this.loadData({ currentPage: 1 })
    },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {}
      if (this.$route.query.level !== undefined && this.$route.query.level !== null) {
        this.projectlevelList[0] = this.$route.query.level
      }
      if (this.$route.query.abnormalstate !== undefined && this.$route.query.abnormalstate !== null) {
        this.queryParam.qry_abnormalstate = this.$route.query.abnormalstate
      }
      if (this.$route.query.projectstate !== undefined && this.$route.query.projectstate !== null) {
        this.queryParam.qry_projectstate = this.$route.query.projectstate
      }
      if (this.projectlevelList && this.projectlevelList.length > 0) {
        param.qry_projectlevel = this.projectlevelList.join(',')
      }
      if (this.superQueryParams) {
        param['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      if (this.urlParam.length !== 0) {
        this.urlParam = window.location.search
      }
      Object.assign(param, this.queryParam, this.sorterInfo, this.filtersInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return filterObjectNull(param)
    },
    // 禁用表格前面的选择
    doDisableCheckBox(row, index) {
      if (row.state !== 0 && row.state !== 2) {
        return false
      } else {
        return true
      }
    },
    /** 列表数据加载开始 */
    loadData(paramMap) {
      // 得到加载分页
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      if (!this.beforeLoadData()) return
      // 查询条件
      var params = this.getQueryParams()
      // 数据查询
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            // 内外部产品字段格式转换
            res.result.dataList.forEach((element) => {
              if (element.productrange && element.productrange.length > 0 && !Array.isArray(element.productrange)) {
                let productArray = element.productrange
                productArray = productArray.replace(/\//g, '')
                console.log(JSON.parse(productArray))
                element.productrange = JSON.parse(productArray)
              }
              if (element.productoutrange && element.productoutrange.length > 0 && !Array.isArray(element.productoutrange)) {
                let outProductArray = element.productoutrange
                outProductArray = outProductArray.replace(/\//g, '')
                element.productoutrange = JSON.parse(outProductArray)
              }
            })
            console.log(res.result.dataList)
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
            // 初始化自定义列
            if (typeof this.$refs.toolbar !== 'undefined') {
              this.$refs.toolbar.doInitTableColumn()
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterLoadData()
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    openChangeManager() {
      const param = {
        usercode: this.user.code
      }
      getAction(this.url.getProjectChangeManager, param).then((res) => {
        if (res.success) {
          if (res.result && res.result.length > 0) {
            if (res.result[0].state === 0 || res.result[0].state === 2) {
              this.openEditDialog('projectChangeManager', res.result[0].id)
            } else {
              this.openViewDialog('projectChangeManager', res.result[0].id)
            }
          } else {
            this.openAddDialog('projectChangeManager')
          }
        } else {
          this.$tap.alert('项目经理变更数据未获取成功，请联系管理员')
        }
      })
    },
    isCFO() {
      const param = {
        usercode: this.user.code
      }
      getAction(this.url.isCFO, param).then((res) => {
        if (res.success) {
          if (res.result) {
            this.isCFOForThisProject = true
          }
        } else {
          this.$tap.alert('用户职位未获取成功，请联系管理员')
        }
      })
    },
    expandChange(row, expandedRows) {
      getAction(this.url.queryTaskForSystem, { projectcode: row.projectcode, needsupport: this.queryParam.qry_needsupport })
        .then((res) => {
          if (res.success) {
            let indexRow = row.rowno - (this.pageInfo.currentPage - 1) * this.pageInfo.pageSize - 1
            this.$set(this.datas[indexRow], 'customertask', res.result)
          }
        })
        .catch((err) => {
          this.$tap.alert('加载任务信息出错，请联系管理员！')
        })
    },
    doChangeRowClassName({ row, rowIndex }) {
      if (row.disabledexpand) {
        return 'row-expand-cover'
      }
    },
    afterLoadData() {
      this.expands = []
    },
    /** 打开评论对话框实现 */
    openCommentDialog(editForm, rowData) {
      rowData.target = rowData.projectname
      this.$refs[editForm].isAdd = true
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = false
      this.$refs[editForm].parentModel = rowData
    },
    projectMark(id, type) {
      let params = {
        sourcetype: 'MpmProject',
        sourceid: id,
        operatetype: 'mark',
        usercode: this.user.code,
        type: type,
        whetherleader: '1'
      }
      if (type === '1') {
        for (var i = 0; i < this.datas.length; i++) {
          if (this.datas[i].id === id) {
            this.datas[i].markflag = '1'
            break
          }
        }
      } else {
        for (i = 0; i < this.datas.length; i++) {
          if (this.datas[i].id === id) {
            this.datas[i].markflag = '0'
            break
          }
        }
      }
      postAction(this.url.changeOperateMarkState, params)
        .then((res) => {
          if (res.success) {
            if (type === '1') {
              this.$tap.alert('关注成功！')
            } else if (type === '2') {
              this.$tap.alert('取消关注成功！')
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
    }
  },
  created() {
    // 判断是否为省区财经副总
    this.isCFO()
  },
  mounted() {
    const resizeOb = new ResizeObserver((entries) => {
      const tableEl = entries[0].target
      this.tableWidth = tableEl.clientWidth - 90 + 'px'
    })
    resizeOb.observe(this.$refs.mainTable.$el)
    this.$once('hook:beforeDestroy', () => {
      resizeOb.disconnect()
    })
  }
}
</script>

<style scoped>
div.superviser:hover,
div.superviser:active {
  text-decoration: underline;
}
.app-container >>> .el-table tbody tr:hover > td {
  background-color: transparent !important;
}
.app-container >>> #searchDetailForm .el-form-item__content {
  width: 70%;
}
.app-container >>> #searchDetailForm .el-form-item {
  width: 100%;
}
.superviser {
  display: flex;
}
.superviserButton {
  margin-left: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 22px;
}
::v-deep .el-table .row-expand-cover .cell .el-table__expand-icon {
  display: none;
}
</style>
